import org.junit.Test;
import test.ListNode;

/**
 * 合并两个有序链表
 */
public class MergeOrderList {

    @Test
    public void MergeOrderList() {

        ListNode n3 = new ListNode(4);
        ListNode n2 = new ListNode(2, n3);
        ListNode l1 = new ListNode(1, n2);

        ListNode n23 = new ListNode(4);
        ListNode n22 = new ListNode(3, n23);
        ListNode l2 = new ListNode(1, n22);

        long startTime1 = System.currentTimeMillis();
        ListNode listNode1 = margeTwoLists(l1, l2);
        long endTime1 = System.currentTimeMillis();
        System.out.println("listNode1=" + listNode1 + ",使用时间:" + (endTime1 - startTime1));

//        long startTime2 = System.currentTimeMillis();
//        ListNode listNode2 = margeTwoLists2(l1, l2);
//        long endTime2 = System.currentTimeMillis();
//        System.out.println("listNode2=" + listNode2 + ",使用时间:" + (endTime2 - startTime2));

    }

    /**
     * 方法一：使用循环方法
     */
    public ListNode margeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;

        ListNode resultNote = new ListNode(0);
        ListNode p = resultNote;
        while (l1 != null && l2 != null) {
            if (l1.getVal() < l2.getVal()) {
                p.setNext(l1);
                l1 = l1.getNext();
            } else {
                p.setNext(l2);
                l2 = l2.getNext();
            }
            p = p.getNext();
        }

        if (l1 != null) {
            p.setNext(l1);
        }
        if (l2 != null) {
            p.setNext(l2);
        }
        return resultNote.getNext();
    }
//
//    /**
//     * 方法2 递归
//     */
//    public ListNode margeTwoLists2(ListNode l1, ListNode l2) {
//        if (l1 == null) return l2;
//        if (l2 == null) return l1;
//        if (l1.getVal() < l2.getVal()) {
//            l1.setNext(margeTwoLists2(l1.getNext(), l2));
//            return l1;
//        }
//        l2.setNext(margeTwoLists2(l1, l2.getNext()));
//        return l2;
//    }

}
